package v1

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"

	bc "application/blockchain"
	"application/pkg/app"
)

type BadRecord struct {
	Name    string `json:"name" form:"name"`
	IdCard  string `json:"id_card" form:"id_card"`
	IsLock  string `json:"is_lock" form:"is_lock"`
	AddTime string `json:"add_time" form:"add_time"`
}
type SelectBadRecord struct {
	Name   string `json:"name" form:"name"`
	IdCard string `json:"id_card" form:"id_card"`
}

func AddBadRecord(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(BadRecord)
	err := c.ShouldBind(body)
	if err != nil {
		appG.Response(http.StatusBadRequest, "失败！", fmt.Sprintf("参数出错%s", err.Error()))
		return
	}
	AddTime := time.Now().Format("2006-01-02 15:04:05")
	var bodyBytes [][]byte
	bodyBytes = append(bodyBytes, []byte(body.Name))
	bodyBytes = append(bodyBytes, []byte(body.IdCard))
	bodyBytes = append(bodyBytes, []byte(body.IsLock))
	bodyBytes = append(bodyBytes, []byte(AddTime))
	//调用智能合约
	resp, err := bc.ChannelExecute("add-bad-record", bodyBytes)
	if err != nil {
		appG.Response(http.StatusBadRequest, "调用智能合约失败！", err.Error())
		return
	}
	var data map[string]interface{}
	err = json.Unmarshal(bytes.NewBuffer(resp.Payload).Bytes(), &data)
	if err != nil {
		appG.Response(http.StatusBadRequest, "反序列化失败！", err.Error())
		return
	}
	appG.Response(http.StatusOK, "不良信息上链成功！", data)
}
func QueryBadRecord(c *gin.Context) {
	appG := app.Gin{C: c}
	body := new(SelectBadRecord)
	err := c.ShouldBind(body)
	if err != nil {
		appG.Response(http.StatusBadRequest, "验证参数失败！", err.Error())
		return
	}
	fmt.Println(body.Name)
	fmt.Println("id_card", body.IdCard)
	var bodyBytes [][]byte
	bodyBytes = append(bodyBytes, []byte(body.Name))
	bodyBytes = append(bodyBytes, []byte(body.IdCard))
	//调用智能合约
	resp, err := bc.ChannelQuery("query-bad-record", bodyBytes)
	if err != nil {
		appG.Response(http.StatusBadRequest, "调用智能合约失败！", err.Error())
		return
	}
	//反序列化
	var data []map[string]interface{}
	err = json.Unmarshal(bytes.NewBuffer(resp.Payload).Bytes(), &data)
	if err != nil {
		appG.Response(http.StatusBadRequest, "反序列化失败！", err.Error())
		return
	}
	if len(data) == 0 {
		appG.Response(http.StatusOK, "该用户不在本系统中！", nil)
		return
	}
	appG.Response(http.StatusOK, "查询成功！", data)
}
